package basic.study.leetcode;

import basic.study.leetcode.Mid94.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName interview37
 * @Description
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/25 17:03
 * @Version 1.0
 */
public class interview37 {
    class Codec {
        public String serialize(TreeNode root) {
            if (root == null) return "[]";

            StringBuilder sb = new StringBuilder("[");
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                if (node != null) {
                    sb.append(String.valueOf(node.val) + ",");
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
            }
            sb.deleteCharAt(sb.length()-1);
            sb.append("]");
            return sb.toString();
        }

        public TreeNode deserialize(String data) {
            if (data == "[]") return null;
            String[] strs = data.substring(1, data.length()-1).split(",");
            int i = 1;
            TreeNode root = new TreeNode(Integer.valueOf(strs[0]));
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                if (!strs[i].equals("null")) {
                    node.left = new TreeNode(Integer.valueOf(strs[i]));
                    queue.add(node.left);
                }
                i++;
                if (!strs[i].equals("null")) {
                    node.right = new TreeNode(Integer.valueOf(strs[i]));
                    queue.add(node.right);
                }
                i++;
            }
            return root;

        }
    }
}
//    作者：jyd
//    链接：https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/solution/mian-shi-ti-37-xu-lie-hua-er-cha-shu-ceng-xu-bian-/
//    来源：力扣（LeetCode）
//    著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
